<?php

namespace App\Http\Controllers\Personal;

use App\Facades\Site;
use App\Jobs\CompanyResumePush;
use App\Models\Api\CompanyContact;
use App\Models\Common\CollArea;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyDepartment;
use App\Models\Company\CompanyUser;
use App\Models\Personal\ResumeSend;
use App\Models\Personal\Resume;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Company\CompanyJob;
use Style;

class ResumeSendController extends CommonController{
    /**
     * 简历投递记录
     * @param Request $request
     * @return mixed
     */
    public function resumeSend(Request $request){
        $user = auth()->guard('personal')->user();
        $resume = Resume::where('default', 1)->where('uid', $user->uid)->first(['id']);
        if(empty($resume)){
            return Style::view('personal.warmtips');
        }
        //关键词搜索
        $keyword = trim($request->keyword);
        $job_status = $request->job_status;
        //获取面试通知记录
        $resume_send = DB::table('resume_send as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_job as t3', 't1.job_id', '=', 't3.id')
            ->select(
                't1.created_at', 't1.updated_at', 't1.id', 't1.status', 't1.com_id', 't1.job_id',
                't2.company_name',
                't3.job_title'
            )
            ->where('t1.personal_uid', $user->uid)
            ->where('t1.resume_id', $resume->id)
            ->where(function($query) use ($job_status){
                if($job_status != ''){
                    $query->where('t1.status', $job_status);
                }
            })
            ->where('t1.status', '!=', 4)
            ->where(function($query) use ($keyword){
                if(strlen($keyword) > 0){
                    $query->where('t3.job_title', 'like', '%' . $keyword . '%')
                        ->orWhere('t2.company_name', 'like', '%' . $keyword . '%');
                }
            })
            ->orderBy('updated_at', 'desc')
            ->paginate(10);

        //处理数组
        foreach($resume_send as $v){
            $v->company_name = str_limit($v->company_name, 24);
            $v->job_title = str_limit($v->job_title, 24);
            $v->created_at = substr($v->created_at, 0, 16);
            $v->updated_at = substr($v->updated_at, 0, 16);
            switch($v->status){
                case 0 :
                    $v->statusval = '未查看';
                    break;
                case 1 :
                    $v->statusval = 'HR已查看';
                    break;
                case 2 :
                    $v->statusval = '同意面试';
                    break;
                case 3 :
                    $v->statusval = '已被婉拒';
                    break;
                case 4 :
                    $v->statusval = '删除';
            }
        }
        //分页分配参数 过滤空值
        $appends = arrayFilter(array(
            'keyword' => $keyword,
            'job_status' => $job_status
        ));

        return Style::view('personal.resumeSend', compact('resume_send', 'job_status', 'appends'));
    }

    /**
     * 投递记录删除
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function postDel(Request $request){
        $user = auth()->guard('personal')->user();
        $selected_id = $request->input('selected_id.*');
        $input['status'] = 4;
        $input['updated_at'] = date('Y-m-d H:i:s', time());
        foreach($selected_id as $v){
            ResumeSend::where('id', $v)->where('personal_uid', $user->uid)->update($input);
        }
        return redirect('personal/resume_send');
    }

    /**
     * 撤销投递
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postUndo(Request $request){
        $user = auth()->guard('personal')->user();
        $input['status'] = 4;
        $input['updated_at'] = date('Y-m-d H:i:s', time());
        $result = ResumeSend::where('id', $request->id)->where('personal_uid', $user->uid)->update($input);
        if($result){
            return response()->json(['status' => 0, 'msg' => '撤销投递成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '撤销投递失败，请稍后重试！']);
        }
    }

    /**
     * 投递记录展开详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postInfo(Request $request){
        $user = auth()->guard('personal')->user();
        //浏览职位
        $browse_resume = DB::table('browse_resume')->select('id', 'updated_at')->where('personal_uid', $user->uid)
            ->where('com_id', $request->com_id)->orderBy('updated_at', 'desc')->first();
        if(!empty($browse_resume)){
            $browse_resume->updated_at = substr($browse_resume->updated_at, 0, 16);
        }else{
            $browse_resume = array();
        }
        //处理数组
        if(!empty($browse_resume)){
            $status = 1;
        }else{
            $status = 0;
        }
        //面试记录
        $interview = DB::table('interview as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->select(
                't1.id', 't1.interview_time', 't1.updated_at',
                't2.company_name', 't2.region', 't2.contacts', 't2.mobile', 't2.phone'
            )
            ->where('t1.personal_uid', $user->uid)
            ->where('t1.com_id', $request->com_id)
            ->where('t1.job_id', $request->job_id)
            ->orderBy('updated_at', 'desc')
            ->first();
        //处理数组
        if(!empty($interview)){
            $interview->region = str_limit(str_replace(',', '', CollArea::getCityAddress($interview->region)), 18);
            $interview->interview_time = substr($interview->interview_time, 0, 16);
            $interview->phone = ($interview->mobile) ? $interview->mobile : $interview->phone;
        }else{
            $interview = array();
        }
        if(!empty($interview)){
            $interview_status = 1;
        }else{
            $interview_status = 0;
        }
        return response()->json(['status' => $status, 'browse_resume' => $browse_resume, 'interview_status' => $interview_status, 'interview' => $interview]);
    }

    /**
     * form简历投递申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    //form简历投递申请
    public function applyJob(Request $request){
        $request->only('jobid');
        $jobid = $request->jobid;
        //个人用户登录
        $user = auth()->guard('personal')->user();

        if(!empty($user->uid)){//登录

            //查询企业uid 与comid
            $companyInfo = CompanyJob::select('com_id', 'uid', 'id', 'contact_info')->where('id', $jobid)->first();

            //查看用户状态
            $personStatus = Resume::select('id', 'resume_status')->where('default', 1)->where('uid', $user->uid)->first();//用户简历信息
            $applyJob = ResumeSend::select('status', 'created_at')->where('job_id', $jobid)->where('personal_uid', $user->uid)
                ->orderBy('created_at', 'desc')->first();//申请职位信息

            $applyJobStatus = '';
            $applyJobMsg = '';
            $contract='';
            $showStatus=false;
            if($personStatus and $personStatus->resume_status != 4){//有简历,且不等于4

                if($applyJob){//已申请了
                    //超过一星期，可以重新投递，当前时间减去创建时间+7
                    if(strtotime(date("Y-m-d H:i:s", time())) - strtotime(date("Y-m-d H:i:s", strtotime(' 7 day', strtotime($applyJob->created_at)))) > 0){
                        $applyJobStatus = 0;
                        $applyJobMsg = '您的简历投递成功！';
                        //发送简历库里加一份
                        $applyData['company_uid'] = $companyInfo->uid;
                        $applyData['com_id'] = $companyInfo->com_id;
                        $applyData['personal_uid'] = $user->uid;
                        $applyData['resume_id'] = $personStatus->id;
                        $applyData['job_id'] = $jobid;
                        $applyData['status'] = 0;
                        $applyData['created_at'] = date('Y-m-d H:i:s');
                        $applyData['updated_at'] = date('Y-m-d H:i:s');
                        $apply = ResumeSend::create($applyData);
                        $this->messagePush($apply);
                    }else{
                        switch($applyJob->status){
                            case 0://未处理
                                $applyJobStatus = 0;
                                $applyJobMsg = '您已申请过该岗位！';
                                break;
                            case 1://已查看
                                $applyJobStatus = 0;
                                $applyJobMsg = '企业已查看了您的简历，请等待消息！';
                                break;
                            case 2://同意邀约
                                $applyJobStatus = 0;
                                $applyJobMsg = '企业已查看了您的简历，已同意邀约面试！';
                                break;
                            case 3://已被婉拒
                                $applyJobStatus = 1;
                                $applyJobMsg = '抱歉，您的简历已被婉拒！';
                                break;
                            case 4://已被删除
                                $applyJobStatus = 1;
                                $applyJobMsg = '抱歉，您的简历已被婉拒！';
                                break;
                            default:
                                $applyJobStatus = 1;
                                $applyJobMsg = '没有查到您的相关信息！';
                                break;
                        }
                    }
                }else{
                    $applyJobStatus = 0;
                    $applyJobMsg = '您的简历投递成功！';
                    //发送简历库里加一份
                    $applyData['company_uid'] = $companyInfo->uid;
                    $applyData['com_id'] = $companyInfo->com_id;
                    $applyData['personal_uid'] = $user->uid;
                    $applyData['resume_id'] = $personStatus->id;
                    $applyData['job_id'] = $jobid;
                    $applyData['status'] = 0;
                    $applyData['created_at'] = date('Y-m-d H:i:s');
                    $applyData['updated_at'] = date('Y-m-d H:i:s');
                    $apply = ResumeSend::create($applyData);
                    $this->messagePush($apply);
                    //返回联系方式
                    $contract =  $this->contact($companyInfo);
                    $showStatus = true;//显示联系方式
                }
            }else{//登录且无简历
                $applyJobStatus = 2;
                $applyJobMsg = '您还未创建简历，去创建一份？';
            }

        }else{//未登录
            $applyJobStatus = 1;
            $applyJobMsg = '您还未登录';
        }

        return response()->json(['status' => $applyJobStatus,'showStatus'=>$showStatus, 'msg' => $applyJobMsg,'contact' => $contract]);
    }

    /**
     * 返回联系方式
     * @param $contact_info
     */
    public function contact($companyInfo){
        if(Site::get('member_contact')==2){
            $companyUser = CompanyUser::select('viptime')->where('uid', $companyInfo->uid)->first();
            if($companyUser->viptime<date('Y-m-d H:i:s')){
                return '';
            }
        }
        switch($companyInfo->contact_info){
            case  0 :
                $contract = CompanyBasic::where('id', $companyInfo->com_id)->where('uid', $companyInfo->uid)->first(['mobile', 'phone']);
                break;
            case  1 :
                $contract = CompanyDepartment::where('uid', $companyInfo->uid)->where('com_id', $companyInfo->com_id)->first(['mobile', 'phone']);
                break;
            case  2 :
                $contract = CompanyContact::where('uid', $companyInfo->uid)->where('job_id', $companyInfo->id)->first(['mobile', 'phone']);
                break;
            case  3 :
                $contract = '';
                break;
        }
        return $contract;
    }

    /**
     * 消息推送
     * @param $resumeId
     */
    public function messagePush($data){
        $job = (new CompanyResumePush($data));
        $this->dispatch($job);
    }
}